package org.jash.shop2202.utils

import android.content.Context
import android.content.SharedPreferences
import com.tencent.mmkv.MMKV

sealed interface StoreUtils {
    fun put(key:String, value:String)
    fun getString(key:String, defValue:String):String
    fun put(key:String, value:Set<String>)
    fun getStringSet(key:String, defValue:Set<String>):Set<String>
    private data class SPUtils(val sp:SharedPreferences):StoreUtils {
        override fun put(key: String, value: String) {
            sp.edit().putString(key, value).apply()
        }

        override fun put(key: String, value: Set<String>) {
            sp.edit().putStringSet(key, value).apply()
        }

        override fun getString(key: String, defValue: String):String {
            return sp.getString(key, defValue) ?: defValue
        }

        override fun getStringSet(key: String, defValue: Set<String>): Set<String> {
            return sp.getStringSet(key, defValue) ?: defValue
        }
    }

    private object MMKVUtils:StoreUtils {
        override fun put(key: String, value: String) {
            MMKV.defaultMMKV().encode(key, value)
        }

        override fun put(key: String, value: Set<String>) {
            MMKV.defaultMMKV().encode(key, value)
        }

        override fun getString(key: String, defValue: String):String {
            return MMKV.defaultMMKV().decodeString(key, defValue) ?: defValue
        }

        override fun getStringSet(key: String, defValue: Set<String>): Set<String> {
            return MMKV.defaultMMKV().decodeStringSet(key, defValue) ?: defValue
        }
    }
    companion object {
        private var instance:StoreUtils? = null
        fun init(context: Context, type:String) {
            instance = when(type) {
                "SP" -> SPUtils(context.getSharedPreferences("store", Context.MODE_PRIVATE))
                "MMKV" -> {
                    MMKV.initialize(context)
                    MMKVUtils
                }
                else -> null
            }
        }
        fun getUtils():StoreUtils {
            if (instance !=null) {
                return instance!!
            }
            throw RuntimeException("使用StoreUtils前要初始化")
        }
    }
}